;(function() {
  // 初始设置body高度
  var eleMain = document.getElementById('app'),
    progressBar = document.getElementById('progressbar'),
    // pageButtons = document.getElementById('page-button').children,
    scrollLine = document.getElementById('scroll-line'),
    zoomImg = eleMain.querySelector('img.pic'),
    mainHeight = eleMain.offsetHeight,
    currentScrollTop,
    currentFloor, // 当前所在 层
    nextFloor = 1, // 滚动的 下一层
    isSlide = true,
    timerId = null,
    blockSlide = true,
    scrollIndicator
  // 获取视口高度
  var { height: viewportHeight } = getViewport()

  // 全屏鼠标滚动 平滑过渡

  /**
   *  需求:
   *    1. 鼠标滚轮滚动 实现平滑滚动到下一层 [✗]
   *    2. 点击侧边按钮 平滑滚动到下一层 [✓]
   *    3. 顶部进度指示器 [✓]
   *
   *  初始思路：
   *    1. 模拟点击事件， CSS属性: scroll-behavior: smooth; hash锚点跳转
   *    2. Promise 取消事件
   *
   *  问题: 需要#app 与 body 的相互监控
   *      当 app滚动 需要 window.scrollTo 改变 body滚动位置
   *      当 模拟点击事件或者 window.scrollTo 触发 app 的滚动
   *
   *      然而 app 的 scrollTo 无法实现
   *
   *  问题: 给 body 设置 position: fixed;top: 5px;bottom: 0; 之后， 锚点跳转失效
   *
   *  问题: CSS 顶部进度条 背景层叠问题 如果有背景，覆盖父元素背景
   *  TODO: 使用JS定义滚动条
   *
   */

  // EventUtil.addHandler(document, 'mousewheel', handleMouseWheel)
  // EventUtil.addHandler(document, 'DOMMouseScroll', handleMouseWheel)
  // EventUtil.addHandler(window, 'scroll', handleMouseWheel)
  // 内部独立方法

  function once() {
    if (blockSlide) {
      console.log('do something')

      // pageButtons[(currentFloor + 1) % 4].querySelectorAll('a')[0].click()
      // console.log(pageButtons[(currentFloor + 1) % 4].querySelectorAll('a')[0])

      blockSlide = false

      window.scrollTo(0, (currentFloor + 2) * viewportHeight)

      // document.documentElement.scrollTop = (currentFloor + 1) % 4 * viewportHeight
    } else {
      // TODO: 判断当前位置？？？
      console.info(
        'if your place is in next floor, you can do it!!' +
          'currentFloor:' +
          currentFloor
      )

      return
    }
  }

  function handleMouseWheel(event) {
    // 窗口顶部滚动条
    currentScrollTop = document.documentElement.scrollTop
    scrollIndicator = (currentScrollTop / (mainHeight - viewportHeight)) * 100
    scrollLine.style.width = scrollIndicator + '%'

    // header 图片zoom
    zoomImg.style.cssText = `width: ${currentScrollTop / 5 +
      100}%; top: ${-currentScrollTop /
      10}%; -webkit-filter: blur${currentScrollTop /
      200}px; filter: blur(${currentScrollTop / 200}px);`

    // event = EventUtil.getEvent(event)
    // // let delta = EventUtil.getWheelDelta(event);

    // EventUtil.preventDefault(event)
    // EventUtil.stopPropagation(event)

    currentFloor = parseInt(currentScrollTop / viewportHeight) || 0

    // 获取 nextFloor

    // EventUtil.removeHandler(document, 'mousewheel', handleMouseWheel)
    // EventUtil.removeHandler(document, 'DOMMouseScroll', handleMouseWheel)
    // once()

    if (currentFloor === nextFloor) {
      nextFloor = (nextFloor + 1) % 4
      // console.log('current: ' + currentFloor, 'next' + nextFloor)
    } else {
      // nextFloor =
    }

    if (-5 < currentScrollTop - viewportHeight * currentFloor < 5) {
      console.log(currentScrollTop, viewportHeight * nextFloor)
    }
  }

  // TODO: 点击触发事件( 含模拟点击 )
  //    1. 所有的点击 都要重写为 window.scrollTo
  //    2. 鼠标滚轮，模拟点击事件 判断位置 currentFloor

  var ticking = false
  var scrollSensitivitySetting = 60
  var slideDurationSetting = 600
  var currentSlideNumber = 0
  var slideItems = document.querySelectorAll('.section')
  var totalSlideNumber = slideItems.length

  // EventUtil.addHandler(window, 'scroll', throttle(60, parallaxScroll))
  // EventUtil.addHandler(document, 'DOMMouseScroll', throttle(60, parallaxScroll))
  window.addEventListener('mousewheel', throttle(parallaxScroll, 60, 100))

  function parallaxScroll(event) {
    var delta = EventUtil.getWheelDelta(event)

    if (!ticking) {
      if (delta <= -scrollSensitivitySetting) {
        // Down
        ticking = true
        if (currentSlideNumber !== totalSlideNumber - 1) {
          currentSlideNumber++
          nextItem()
        }

        slideDurationTimeout(slideDurationSetting)
      }
      if (delta >= scrollSensitivitySetting) {
        ticking = true
        if (currentSlideNumber !== 0) {
          currentSlideNumber--
        }

        previousItem()
        slideDurationTimeout(slideDurationSetting)
      }
    }
  }

  // 节流函数
  function throttle(fn, delay, mustRunDelay) {
    var timer = null
    var t_start
    return function() {
      var context = this,
        args = arguments,
        t_curr = +new Date()
      clearTimeout(timer)
      if (!t_start) {
        t_start = t_curr
      }
      if (t_curr - t_start >= mustRunDelay) {
        fn.apply(context, args)
        t_start = t_curr
      } else {
        timer = setTimeout(function() {
          fn.apply(context, args)
        }, delay)
      }
    }
  }

  function slideDurationTimeout(slideDuration) {
    setTimeout(function() {
      ticking = false
    }, slideDuration)
  }

  function nextItem() {
    var previousSlide = slideItems[currentSlideNumber - 1]

    previousSlide.classList.remove('up-scroll')
    previousSlide.classList.add('down-scroll')

    if (currentSlideNumber - 1 === 2) {
      var myCard = slideItems[currentSlideNumber].getElementsByClassName(
        'mycard'
      )[0]

      myCard.classList.add('animated')
      myCard.classList.add('fadeInRight')
    }
  }

  function previousItem() {
    var currentSlide = slideItems[currentSlideNumber]

    currentSlide.classList.remove('down-scroll')
    currentSlide.classList.add('up-scroll')
    console.log(currentSlideNumber)
  }

  // 经历页面 滚动
  var eleDot = document.querySelector('#app .dot')
  var dotList = eleDot.querySelectorAll('li')
  var historyCards = document.querySelectorAll('#part4 .mycard > li')

  EventUtil.addHandler(eleDot, 'click', function(e) {
    if (e.target == eleDot) {
      return
    }
    dotList.forEach((item, index) => {
      if (item != e.target) {
        item.classList.remove('active')
        historyCards[index].classList.remove('lightSpeedIn')

        historyCards[index].style.display = 'none'
      } else {
        item.classList.add('active')
        historyCards[index].style.display = 'block'

        historyCards[index].classList.add('lightSpeedIn')
      }
    })
  })

  // 发送 表单 请求
  var form = document.getElementsByTagName('form')[0]
  EventUtil.addHandler(form, 'submit', async function() {
    event = EventUtil.getEvent(event)
    var target = EventUtil.getTarget(event)

    // 阻止默认事件
    EventUtil.preventDefault(event)
    var btn = target.elements['submit-btn']
    btn.disabled = true

    var data = new FormData(comment)
    data.append('app1', 'append1')
    data.append('app2', 'append2')

    // TODO: request 失败
    await fetch('/api/post-data', {
      body: data,
      headers: new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
      }),
      method: 'POST'
    })
      .then(res => {
        console.log(res)
      })
      .catch(err => console.error(err))
  })
})()
